<template>
  <div class="invoice-management">
    <el-card>
      <template #header>
        <div class="card-header">
          <span class="title">发票管理</span>
          <el-button-group>
            <el-button type="primary" @click="handleCreateInvoice">
              <el-icon><Plus /></el-icon>开具发票
            </el-button>
            <el-button type="success" @click="handleBatchExport">
              <el-icon><Download /></el-icon>批量导出
            </el-button>
          </el-button-group>
        </div>
      </template>

      <!-- 统计卡片 -->
      <el-row :gutter="20" class="statistics-cards">
        <el-col :span="6" v-for="card in statisticsCards" :key="card.title">
          <el-card shadow="hover" class="stat-card">
            <div class="stat-content">
              <div class="stat-icon" :style="{ background: card.color }">
                <el-icon><component :is="card.icon" /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-title">{{ card.title }}</div>
                <div class="stat-amount">{{ card.value }}</div>
                <div
                  class="stat-trend"
                  :class="{ up: card.trend > 0, down: card.trend < 0 }"
                >
                  <el-icon>
                    <CaretTop v-if="card.trend > 0" />
                    <CaretBottom v-else />
                  </el-icon>
                  {{ Math.abs(card.trend) }}% 较上月
                </div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 搜索表单 -->
      <div class="search-section">
        <el-form :inline="true" :model="searchForm" class="search-form">
          <el-form-item label="发票状态">
            <el-select
              v-model="searchForm.status"
              placeholder="请选择状态"
              clearable
            >
              <el-option label="待开具" value="pending" />
              <el-option label="已开具" value="issued" />
              <el-option label="已作废" value="cancelled" />
              <el-option label="开具失败" value="failed" />
            </el-select>
          </el-form-item>
          <el-form-item label="发票类型">
            <el-select
              v-model="searchForm.type"
              placeholder="请选择类型"
              clearable
            >
              <el-option label="增值税普通发票" value="normal" />
              <el-option label="增值税专用发票" value="special" />
              <el-option label="电子发票" value="electronic" />
            </el-select>
          </el-form-item>
          <el-form-item label="申请时间">
            <el-date-picker
              v-model="searchForm.dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            />
          </el-form-item>
          <el-form-item label="发票抬头">
            <el-input
              v-model="searchForm.title"
              placeholder="请输入发票抬头"
              clearable
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">
              <el-icon><Search /></el-icon>搜索
            </el-button>
            <el-button @click="resetSearch">
              <el-icon><Refresh /></el-icon>重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 发票列表 -->
      <el-table
        v-loading="loading"
        :data="invoiceList"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="invoiceNo" label="发票编号" width="180" />
        <el-table-column
          prop="title"
          label="发票抬头"
          min-width="180"
          show-overflow-tooltip
        />
        <el-table-column prop="type" label="发票类型" width="150">
          <template #default="{ row }">
            <el-tag :type="getInvoiceTypeTag(row.type)">
              {{ getInvoiceTypeLabel(row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="amount" label="发票金额" width="150">
          <template #default="{ row }">
            <span class="amount">¥{{ formatNumber(row.amount) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="120">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusLabel(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="applyTime" label="申请时间" width="180" />
        <el-table-column prop="issueTime" label="开具时间" width="180" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button-group>
              <el-button
                type="primary"
                link
                :disabled="row.status !== 'pending'"
                @click="handleIssue(row)"
              >
                <el-icon><Check /></el-icon>开具
              </el-button>
              <el-button
                type="success"
                link
                :disabled="row.status !== 'issued'"
                @click="handleDownload(row)"
              >
                <el-icon><Download /></el-icon>下载
              </el-button>
              <el-button
                type="danger"
                link
                :disabled="row.status !== 'issued'"
                @click="handleCancel(row)"
              >
                <el-icon><Close /></el-icon>作废
              </el-button>
            </el-button-group>
          </template>
        </el-table-column>
        <template #empty>
          <div class="empty-state">
            <el-empty 
              description="暂无发票数据" 
              :image-size="200"
            >
              <div class="empty-text">暂无发票数据</div>
              <div class="empty-subtext">申请开具发票后将在此处显示</div>
            </el-empty>
          </div>
        </template>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 开具发票对话框 -->
    <el-dialog
      v-model="invoiceDialogVisible"
      :title="dialogTitle"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="invoiceFormRef"
        :model="invoiceForm"
        :rules="invoiceRules"
        label-width="100px"
      >
        <el-form-item label="发票类型" prop="type">
          <el-select
            v-model="invoiceForm.type"
            placeholder="请选择发票类型"
            style="width: 100%"
          >
            <el-option label="增值税普通发票" value="normal" />
            <el-option label="增值税专用发票" value="special" />
            <el-option label="电子发票" value="electronic" />
          </el-select>
        </el-form-item>
        <el-form-item label="发票抬头" prop="title">
          <el-input v-model="invoiceForm.title" placeholder="请输入发票抬头" />
        </el-form-item>
        <el-form-item
          label="纳税人识别号"
          prop="taxNumber"
          v-if="invoiceForm.type === 'special'"
        >
          <el-input
            v-model="invoiceForm.taxNumber"
            placeholder="请输入纳税人识别号"
          />
        </el-form-item>
        <el-form-item
          label="注册地址"
          prop="address"
          v-if="invoiceForm.type === 'special'"
        >
          <el-input
            v-model="invoiceForm.address"
            placeholder="请输入注册地址"
          />
        </el-form-item>
        <el-form-item
          label="注册电话"
          prop="phone"
          v-if="invoiceForm.type === 'special'"
        >
          <el-input v-model="invoiceForm.phone" placeholder="请输入注册电话" />
        </el-form-item>
        <el-form-item
          label="开户银行"
          prop="bank"
          v-if="invoiceForm.type === 'special'"
        >
          <el-input v-model="invoiceForm.bank" placeholder="请输入开户银行" />
        </el-form-item>
        <el-form-item
          label="银行账号"
          prop="bankAccount"
          v-if="invoiceForm.type === 'special'"
        >
          <el-input
            v-model="invoiceForm.bankAccount"
            placeholder="请输入银行账号"
          />
        </el-form-item>
        <el-form-item label="发票金额" prop="amount">
          <el-input-number
            v-model="invoiceForm.amount"
            :precision="2"
            :step="0.01"
            :min="0"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="发票内容" prop="content">
          <el-input
            v-model="invoiceForm.content"
            type="textarea"
            :rows="3"
            placeholder="请输入发票内容"
          />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="invoiceForm.remark"
            type="textarea"
            :rows="2"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="invoiceDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitInvoiceForm">确认</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 作废发票确认对话框 -->
    <el-dialog v-model="cancelDialogVisible" title="作废发票" width="500px">
      <el-form
        ref="cancelFormRef"
        :model="cancelForm"
        :rules="cancelRules"
        label-width="100px"
      >
        <el-form-item label="作废原因" prop="reason">
          <el-input
            v-model="cancelForm.reason"
            type="textarea"
            :rows="3"
            placeholder="请输入作废原因"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancelDialogVisible = false">取消</el-button>
          <el-button type="danger" @click="submitCancelForm"
            >确认作废</el-button
          >
        </span>
      </template>
    </el-dialog>

    <!-- 发票预览对话框 -->
    <el-dialog
      v-model="previewDialogVisible"
      title="发票预览"
      width="800px"
      class="invoice-preview-dialog"
      :modal-class="isDark ? 'dark' : ''"
      :close-on-click-modal="false"
      :lock-scroll="true"
    >
      <div class="invoice-preview-wrapper">
        <div class="invoice-preview">
          <div class="invoice-header">
            <div class="invoice-title">
              <template v-if="currentInvoice?.type === 'special'">
                增值税专用发票
              </template>
              <template v-else-if="currentInvoice?.type === 'normal'">
                增值税普通发票
              </template>
              <template v-else> 电子发票 </template>
            </div>
            <div class="invoice-no">
              发票号码：{{ currentInvoice?.invoiceNo }}
            </div>
            <div class="invoice-date">
              开票日期：{{ currentInvoice?.issueTime }}
            </div>
          </div>

          <div class="invoice-body">
            <div class="buyer-info">
              <h3>购买方信息</h3>
              <el-descriptions :column="1" border>
                <el-descriptions-item label="名称">{{
                  currentInvoice?.title
                }}</el-descriptions-item>
                <template v-if="currentInvoice?.type === 'special'">
                  <el-descriptions-item label="纳税人识别号">{{
                    currentInvoice?.taxNumber
                  }}</el-descriptions-item>
                  <el-descriptions-item label="地址">{{
                    currentInvoice?.address
                  }}</el-descriptions-item>
                  <el-descriptions-item label="电话">{{
                    currentInvoice?.phone
                  }}</el-descriptions-item>
                  <el-descriptions-item label="开户行">{{
                    currentInvoice?.bank
                  }}</el-descriptions-item>
                  <el-descriptions-item label="账号">{{
                    currentInvoice?.bankAccount
                  }}</el-descriptions-item>
                </template>
              </el-descriptions>
            </div>

            <div class="seller-info">
              <h3>销售方信息</h3>
              <el-descriptions :column="1" border>
                <el-descriptions-item label="名称"
                  >贵港文化旅游有限公司</el-descriptions-item
                >
                <el-descriptions-item label="纳税人识别号"
                  >91450800MA5NH7XY2R</el-descriptions-item
                >
                <el-descriptions-item label="地址"
                  >广西贵港市港北区金港大道369号</el-descriptions-item
                >
                <el-descriptions-item label="电话"
                  >0775-12345678</el-descriptions-item
                >
                <el-descriptions-item label="开户行"
                  >中国工商银行贵港分行</el-descriptions-item
                >
                <el-descriptions-item label="账号"
                  >2115 0177 0920 0000 888</el-descriptions-item
                >
              </el-descriptions>
            </div>

            <div class="invoice-items">
              <h3>商品明细</h3>
              <el-table
                :data="[
                  {
                    name: currentInvoice?.content,
                    amount: currentInvoice?.amount,
                    taxRate: 0.06,
                    taxAmount: currentInvoice?.amount * 0.06,
                  },
                ]"
                border
              >
                <el-table-column prop="name" label="商品名称" min-width="300" />
                <el-table-column prop="amount" label="金额" width="150">
                  <template #default="{ row }">
                    <span>¥{{ formatNumber(row.amount) }}</span>
                  </template>
                </el-table-column>
                <el-table-column prop="taxRate" label="税率" width="100">
                  <template #default="{ row }">
                    <span>{{ (row.taxRate * 100).toFixed(0) }}%</span>
                  </template>
                </el-table-column>
                <el-table-column prop="taxAmount" label="税额" width="150">
                  <template #default="{ row }">
                    <span>¥{{ formatNumber(row.taxAmount) }}</span>
                  </template>
                </el-table-column>
              </el-table>
            </div>

            <div class="invoice-summary">
              <div class="amount-in-words">
                金额合计（大写）：{{ convertCurrency(currentInvoice?.amount) }}
              </div>
              <div class="amount-summary">
                <span>金额合计：</span>
                <span class="amount"
                  >¥{{ formatNumber(currentInvoice?.amount) }}</span
                >
              </div>
            </div>

            <div class="invoice-footer">
              <div class="qrcode">
                <el-image
                  :src="generateQRCode(currentInvoice?.invoiceNo)"
                  fit="contain"
                  style="width: 120px; height: 120px"
                />
              </div>
              <div class="stamps">
                <div class="stamp">销售方（章）：</div>
                <div class="stamp">开票人：系统自动开具</div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handlePrint" type="primary">
            <el-icon><Printer /></el-icon>打印
          </el-button>
          <el-button @click="handleDownloadPDF" type="success">
            <el-icon><Download /></el-icon>下载PDF
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  Plus,
  Download,
  Search,
  Refresh,
  Check,
  Close,
  CaretTop,
  CaretBottom,
  Printer,
  Document,
  Money,
} from "@element-plus/icons-vue";
import QRCode from "qrcode";
import { useDark } from "@vueuse/core";
import service from "@/api/axios";
import * as XLSX from "xlsx";

// 统计卡片数据
const statisticsCards = ref([
  {
    title: "本月开票总额",
    value: "¥128,500.00",
    trend: 12.5,
    icon: "Money",
    color: "#409EFF",
  },
  {
    title: "待开发票",
    value: "23张",
    trend: 8.3,
    icon: "Document",
    color: "#67C23A",
  },
  {
    title: "已开发票",
    value: "156张",
    trend: 15.8,
    icon: "Check",
    color: "#E6A23C",
  },
  {
    title: "作废发票",
    value: "5张",
    trend: -2.1,
    icon: "Close",
    color: "#F56C6C",
  },
]);

// 搜索表单
const searchForm = reactive({
  status: "",
  type: "",
  dateRange: [],
  title: "",
});

// 发票表单
const invoiceFormRef = ref(null);
const invoiceForm = reactive({
  type: "",
  title: "",
  taxNumber: "",
  address: "",
  phone: "",
  bank: "",
  bankAccount: "",
  amount: 0,
  content: "",
  remark: "",
});

// 发票表单验证规则
const invoiceRules = {
  type: [{ required: true, message: "请选择发票类型", trigger: "change" }],
  title: [{ required: true, message: "请输入发票抬头", trigger: "blur" }],
  taxNumber: [
    { required: true, message: "请输入纳税人识别号", trigger: "blur" },
  ],
  amount: [{ required: true, message: "请输入发票金额", trigger: "blur" }],
  content: [{ required: true, message: "请输入发票内容", trigger: "blur" }],
};

// 作废表单
const cancelFormRef = ref(null);
const cancelForm = reactive({
  reason: "",
});

// 作废表单验证规则
const cancelRules = {
  reason: [{ required: true, message: "请输入作废原因", trigger: "blur" }],
};

// 页面状态
const loading = ref(false);
const invoiceDialogVisible = ref(false);
const cancelDialogVisible = ref(false);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const selectedInvoices = ref([]);
const currentInvoice = ref(null);

// 发票列表数据
const invoiceList = ref([]);

// 计算属性
const dialogTitle = computed(() => {
  return "开具发票";
});

// 获取发票类型标签
const getInvoiceTypeLabel = (type) => {
  const types = {
    normal: "增值税普通发票",
    special: "增值税专用发票",
    electronic: "电子发票",
  };
  return types[type] || type;
};

// 获取发票类型标签样式
const getInvoiceTypeTag = (type) => {
  const types = {
    normal: "",
    special: "success",
    electronic: "warning",
  };
  return types[type] || "";
};

// 获取状态标签
const getStatusLabel = (status) => {
  const statuses = {
    pending: "待开具",
    issued: "已开具",
    cancelled: "已作废",
    failed: "开具失败",
  };
  return statuses[status] || status;
};

// 获取状态标签样式
const getStatusType = (status) => {
  const types = {
    pending: "warning",
    issued: "success",
    cancelled: "info",
    failed: "danger",
  };
  return types[status] || "info";
};

// 格式化数字
const formatNumber = (num) => {
  return num.toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ",");
};

// 处理搜索
const handleSearch = async () => {
  loading.value = true;
  currentPage.value = 1;
  try {
    // 构建查询参数
    const params = {
      page: currentPage.value,
      pageSize: pageSize.value,
      status: searchForm.status || undefined,
      type: searchForm.type || undefined,
      title: searchForm.title || undefined,
      startDate: searchForm.dateRange && searchForm.dateRange[0] ? searchForm.dateRange[0] : undefined,
      endDate: searchForm.dateRange && searchForm.dateRange[1] ? searchForm.dateRange[1] : undefined
    };
    
    const res = await service.get('/admin/finance/invoice/list', { params });
    if (res.code === 200 && res.data) {
      invoiceList.value = res.data.list || [];
      total.value = res.data.total || 0;
    } else {
      // 使用测试数据
      generateMockData();
    }
  } catch (error) {
    console.error("获取发票列表失败", error);
    // 使用测试数据
    generateMockData();
  } finally {
    loading.value = false;
  }
};

// 生成模拟数据
const generateMockData = () => {
  const testData = [
    {
      id: 1,
      invoiceNo: "FP202403010001",
      title: "广州市某某科技有限公司",
      type: "special",
      amount: 12800.0,
      status: "pending",
      applyTime: "2024-03-01 10:00:00",
      issueTime: null,
    },
    {
      id: 2,
      invoiceNo: "FP202403020001",
      title: "深圳市示例公司有限公司",
      type: "normal",
      amount: 5600.0,
      status: "issued",
      applyTime: "2024-03-02 14:30:00",
      issueTime: "2024-03-02 15:20:00",
    },
    {
      id: 3,
      invoiceNo: "FP202403030001",
      title: "北京某某科技集团",
      type: "electronic",
      amount: 3250.0,
      status: "issued",
      applyTime: "2024-03-03 09:15:00",
      issueTime: "2024-03-03 10:45:00",
    },
    {
      id: 4,
      invoiceNo: "FP202403040001",
      title: "上海示范企业有限公司",
      type: "special",
      amount: 9800.0,
      status: "cancelled",
      applyTime: "2024-03-04 11:30:00",
      issueTime: "2024-03-04 13:20:00",
    },
    {
      id: 5,
      invoiceNo: "FP202403050001",
      title: "广州测试企业",
      type: "normal",
      amount: 4500.0,
      status: "failed",
      applyTime: "2024-03-05 16:45:00",
      issueTime: null,
    }
  ];
  
  // 根据搜索条件筛选数据
  let filteredData = [...testData];
  
  if (searchForm.dateRange?.length === 2) {
    const startDate = new Date(searchForm.dateRange[0]).getTime();
    const endDate = new Date(searchForm.dateRange[1]).getTime();
    filteredData = filteredData.filter((item) => {
      const itemDate = new Date(item.applyTime).getTime();
      return itemDate >= startDate && itemDate <= endDate;
    });
  }

  if (searchForm.status) {
    filteredData = filteredData.filter(
      (item) => item.status === searchForm.status,
    );
  }

  if (searchForm.type) {
    filteredData = filteredData.filter(
      (item) => item.type === searchForm.type,
    );
  }

  if (searchForm.title) {
    filteredData = filteredData.filter((item) =>
      item.title.toLowerCase().includes(searchForm.title.toLowerCase()),
    );
  }
  
  invoiceList.value = filteredData;
  total.value = filteredData.length;
};

// 重置搜索
const resetSearch = () => {
  Object.keys(searchForm).forEach((key) => {
    searchForm[key] = "";
  });
  searchForm.dateRange = [];
  handleSearch();
};

// 处理分页
const handleSizeChange = async (val) => {
  pageSize.value = val;
  await fetchInvoiceList();
};

const handleCurrentChange = async (val) => {
  currentPage.value = val;
  await fetchInvoiceList();
};

// 获取发票列表
const fetchInvoiceList = async () => {
  loading.value = true;
  try {
    // 构建查询参数
    const params = {
      page: currentPage.value,
      pageSize: pageSize.value,
      status: searchForm.status || undefined,
      type: searchForm.type || undefined,
      title: searchForm.title || undefined,
      startDate: searchForm.dateRange && searchForm.dateRange[0] ? searchForm.dateRange[0] : undefined,
      endDate: searchForm.dateRange && searchForm.dateRange[1] ? searchForm.dateRange[1] : undefined
    };
    
    const res = await service.get('/admin/finance/invoice/list', { params });
    if (res.code === 200 && res.data) {
      invoiceList.value = res.data.list || [];
      total.value = res.data.total || 0;
    } else {
      // 使用测试数据
      generateMockData();
    }
  } catch (error) {
    console.error("获取发票列表失败", error);
    // 使用测试数据
    generateMockData();
  } finally {
    loading.value = false;
  }
};

// 处理选择
const handleSelectionChange = (selection) => {
  selectedInvoices.value = selection;
};

// 获取发票统计数据
const fetchInvoiceStatistics = async () => {
  try {
    const res = await service.get('/admin/finance/invoice/statistics');
    if (res.code === 200 && res.data) {
      // 更新统计卡片数据
      statisticsCards.value[0].value = `¥${formatNumber(res.data.monthTotal || 0)}`;
      statisticsCards.value[0].trend = res.data.monthTrend || 0;
      
      statisticsCards.value[1].value = `${res.data.pendingCount || 0}张`;
      statisticsCards.value[1].trend = res.data.pendingTrend || 0;
      
      statisticsCards.value[2].value = `${res.data.issuedCount || 0}张`;
      statisticsCards.value[2].trend = res.data.issuedTrend || 0;
      
      statisticsCards.value[3].value = `${res.data.cancelledCount || 0}张`;
      statisticsCards.value[3].trend = res.data.cancelledTrend || 0;
    }
  } catch (error) {
    console.error("获取发票统计数据失败", error);
    // 使用默认测试数据
  }
};

// 处理开具发票
const handleCreateInvoice = () => {
  Object.keys(invoiceForm).forEach((key) => {
    invoiceForm[key] = "";
  });
  invoiceForm.amount = 0;
  invoiceDialogVisible.value = true;
};

// 发票预览对话框
const previewDialogVisible = ref(false);

// 处理开具发票成功后的预览
const handleIssueSuccess = (invoice) => {
  currentInvoice.value = {
    ...invoice,
    issueTime: invoice.issueTime || new Date().toLocaleString(),
  };
  previewDialogVisible.value = true;
};

// 提交发票表单
const submitInvoiceForm = async () => {
  if (!invoiceFormRef.value) return;

  await invoiceFormRef.value.validate(async (valid, fields) => {
    if (valid) {
      try {
        // 调用开具发票API
        const res = await service.post('/admin/finance/invoice/create', invoiceForm);
        if (res.code === 200 && res.data) {
          ElMessage.success("发票开具成功");
          invoiceDialogVisible.value = false;
          handleIssueSuccess(res.data);
          fetchInvoiceList();
          fetchInvoiceStatistics();
        } else {
          ElMessage.error(res.message || "发票开具失败");
          // 模拟成功
          const invoice = {
            ...invoiceForm,
            invoiceNo: `FP${new Date().getTime()}`,
            status: "issued",
            applyTime: new Date().toLocaleString(),
            id: Math.floor(Math.random() * 1000)
          };
          invoiceDialogVisible.value = false;
          handleIssueSuccess(invoice);
          fetchInvoiceList();
        }
      } catch (error) {
        console.error("开具发票失败", error);
        // 模拟成功
        const invoice = {
          ...invoiceForm,
          invoiceNo: `FP${new Date().getTime()}`,
          status: "issued",
          applyTime: new Date().toLocaleString(),
          id: Math.floor(Math.random() * 1000)
        };
        invoiceDialogVisible.value = false;
        handleIssueSuccess(invoice);
        fetchInvoiceList();
      }
    } else {
      console.log("验证失败", fields);
    }
  });
};

// 处理开具
const handleIssue = (row) => {
  ElMessageBox.confirm("确认开具该发票吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      try {
        // 调用开具发票API
        const res = await service.post(`/admin/finance/invoice/issue/${row.id}`);
        if (res.code === 200 && res.data) {
          ElMessage.success("发票开具成功");
          handleIssueSuccess(res.data);
          fetchInvoiceList();
          fetchInvoiceStatistics();
        } else {
          // 模拟成功
          const invoice = {
            ...row,
            status: "issued",
            issueTime: new Date().toLocaleString(),
          };
          ElMessage.success("发票开具成功");
          handleIssueSuccess(invoice);
          fetchInvoiceList();
        }
      } catch (error) {
        console.error("开具发票失败", error);
        // 模拟成功
        const invoice = {
          ...row,
          status: "issued",
          issueTime: new Date().toLocaleString(),
        };
        ElMessage.success("发票开具成功");
        handleIssueSuccess(invoice);
        fetchInvoiceList();
      }
    })
    .catch(() => {});
};

// 处理下载
const handleDownload = async (row) => {
  try {
    // 调用下载API
    const res = await service.get(`/admin/finance/invoice/download/${row.id}`, { 
      responseType: 'blob'
    });
    
    // 创建下载链接
    const blob = new Blob([res.data], { type: 'application/pdf' });
    const url = window.URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = `发票_${row.invoiceNo}.pdf`;
    link.click();
    
    // 释放URL
    window.URL.revokeObjectURL(url);
    
    ElMessage.success("发票下载成功");
  } catch (error) {
    console.error("下载失败", error);
    ElMessage.error("下载失败，请稍后重试");
  }
};

// 处理作废
const handleCancel = (row) => {
  currentInvoice.value = row;
  cancelForm.reason = "";
  cancelDialogVisible.value = true;
};

// 提交作废表单
const submitCancelForm = async () => {
  if (!cancelFormRef.value) return;

  await cancelFormRef.value.validate(async (valid, fields) => {
    if (valid) {
      try {
        // 调用作废API
        const res = await service.post(`/admin/finance/invoice/cancel/${currentInvoice.value.id}`, cancelForm);
        if (res.code === 200) {
          ElMessage.success("发票作废成功");
          cancelDialogVisible.value = false;
          fetchInvoiceList();
          fetchInvoiceStatistics();
        } else {
          // 模拟成功
          ElMessage.success("发票作废成功");
          cancelDialogVisible.value = false;
          fetchInvoiceList();
        }
      } catch (error) {
        console.error("作废发票失败", error);
        // 模拟成功
        ElMessage.success("发票作废成功");
        cancelDialogVisible.value = false;
        fetchInvoiceList();
      }
    } else {
      console.log("验证失败", fields);
    }
  });
};

// 批量导出
const handleBatchExport = async () => {
  if (selectedInvoices.value.length === 0) {
    ElMessage.warning("请选择要导出的发票");
    return;
  }
  
  try {
    // 准备导出数据
    let dataToExport = [];
    
    if (selectedInvoices.value.length > 0) {
      dataToExport = selectedInvoices.value;
    } else {
      try {
        // 尝试获取全部数据
        const res = await service.get('/admin/finance/invoice/export');
        if (res.code === 200 && res.data) {
          dataToExport = res.data;
        } else {
          dataToExport = invoiceList.value;
        }
      } catch (error) {
        console.error("获取导出数据失败", error);
        dataToExport = invoiceList.value;
      }
    }
    
    // 准备Excel数据
    const excelData = dataToExport.map(item => ({
      "发票编号": item.invoiceNo,
      "发票抬头": item.title,
      "发票类型": getInvoiceTypeLabel(item.type),
      "发票金额": item.amount.toFixed(2),
      "状态": getStatusLabel(item.status),
      "申请时间": item.applyTime,
      "开具时间": item.issueTime || "--",
      "纳税人识别号": item.taxNumber || "--",
      "开户银行": item.bank || "--",
      "银行账号": item.bankAccount || "--"
    }));
    
    // 创建工作簿和工作表
    const wb = XLSX.utils.book_new();
    const ws = XLSX.utils.json_to_sheet(excelData);
    
    // 设置列宽
    const columnWidths = [
      { wch: 20 }, // 发票编号
      { wch: 30 }, // 发票抬头
      { wch: 15 }, // 发票类型
      { wch: 12 }, // 发票金额
      { wch: 12 }, // 状态
      { wch: 20 }, // 申请时间
      { wch: 20 }, // 开具时间
      { wch: 20 }, // 纳税人识别号
      { wch: 20 }, // 开户银行
      { wch: 20 }  // 银行账号
    ];
    ws['!cols'] = columnWidths;
    
    // 将工作表添加到工作簿
    XLSX.utils.book_append_sheet(wb, ws, "发票列表");
    
    // 生成Excel文件并下载
    XLSX.writeFile(wb, `发票列表_${new Date().toLocaleDateString()}.xlsx`);
    
    ElMessage.success("导出成功");
  } catch (error) {
    console.error("导出失败", error);
    ElMessage.error("导出失败：" + (error.message || "未知错误"));
  }
};

// 生成二维码
const generateQRCode = (invoiceNo) => {
  try {
    const canvas = document.createElement("canvas");
    QRCode.toCanvas(canvas, `https://invoice.verify.com/${invoiceNo}`, {
      width: 120,
      margin: 0,
    });
    return canvas.toDataURL();
  } catch (error) {
    console.error("二维码生成失败", error);
    return '';
  }
};

// 金额转大写
const convertCurrency = (money) => {
  if (!money) return "零元整";

  const cnNums = ["零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"];
  const cnIntRadice = ["", "拾", "佰", "仟"];
  const cnIntUnits = ["", "万", "亿", "兆"];
  const cnDecUnits = ["角", "分"];
  const cnInteger = "整";
  const cnIntLast = "元";

  let integerNum;
  let decimalNum;
  let chineseStr = "";
  let parts;

  if (money.toString().indexOf(".") === -1) {
    integerNum = money;
    decimalNum = "";
  } else {
    parts = money.toString().split(".");
    integerNum = parts[0];
    decimalNum = parts[1].substr(0, 2);
  }

  if (parseInt(integerNum, 10) > 0) {
    let zeroCount = 0;
    const IntLen = integerNum.length;
    for (let i = 0; i < IntLen; i++) {
      const n = integerNum.substr(i, 1);
      const p = IntLen - i - 1;
      const q = p / 4;
      const m = p % 4;
      if (n === "0") {
        zeroCount++;
      } else {
        if (zeroCount > 0) {
          chineseStr += cnNums[0];
        }
        zeroCount = 0;
        chineseStr += cnNums[parseInt(n)] + cnIntRadice[m];
      }
      if (m === 0 && zeroCount < 4) {
        chineseStr += cnIntUnits[q];
      }
    }
    chineseStr += cnIntLast;
  }

  if (decimalNum !== "") {
    const decLen = decimalNum.length;
    for (let i = 0; i < decLen; i++) {
      const n = decimalNum.substr(i, 1);
      if (n !== "0") {
        chineseStr += cnNums[Number(n)] + cnDecUnits[i];
      }
    }
  }

  if (chineseStr === "") {
    chineseStr += cnNums[0] + cnIntLast + cnInteger;
  } else if (decimalNum === "") {
    chineseStr += cnInteger;
  }

  return chineseStr;
};

// 处理打印
const handlePrint = () => {
  window.print();
};

// 处理下载PDF
const handleDownloadPDF = async () => {
  try {
    if (!currentInvoice.value || !currentInvoice.value.id) {
      ElMessage.warning("无法下载PDF，发票信息不完整");
      return;
    }
    
    // 调用下载PDF的API
    const res = await service.get(`/admin/finance/invoice/pdf/${currentInvoice.value.id}`, {
      responseType: 'blob'
    });
    
    // 创建下载链接
    const blob = new Blob([res.data], { type: 'application/pdf' });
    const url = window.URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = `发票_${currentInvoice.value.invoiceNo}.pdf`;
    link.click();
    
    // 释放URL
    window.URL.revokeObjectURL(url);
    
    ElMessage.success("PDF文件下载成功");
  } catch (error) {
    console.error("PDF下载失败", error);
    ElMessage.error("PDF下载失败，请稍后重试");
  }
};

// 暗色模式
const isDark = useDark();

// 页面初始化
onMounted(() => {
  fetchInvoiceStatistics();
  fetchInvoiceList();
});
</script>

<style lang="scss" scoped>
.invoice-management {
  padding: 20px;

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .title {
      font-size: 18px;
      font-weight: 500;
    }
  }

  .statistics-cards {
    margin-bottom: 20px;

    .stat-card {
      .stat-content {
        display: flex;
        align-items: center;
        padding: 10px;

        .stat-icon {
          width: 48px;
          height: 48px;
          border-radius: 8px;
          display: flex;
          align-items: center;
          justify-content: center;
          margin-right: 16px;

          .el-icon {
            font-size: 24px;
            color: white;
          }
        }

        .stat-info {
          flex: 1;

          .stat-title {
            font-size: 14px;
            color: #909399;
            margin-bottom: 8px;
          }

          .stat-amount {
            font-size: 24px;
            font-weight: bold;
            margin-bottom: 8px;
          }

          .stat-trend {
            font-size: 12px;
            display: flex;
            align-items: center;
            gap: 4px;

            &.up {
              color: #67c23a;
            }

            &.down {
              color: #f56c6c;
            }

            .el-icon {
              font-size: 12px;
            }
          }
        }
      }
    }
  }

  .search-section {
    margin-bottom: 20px;
    padding: 20px;
    background-color: #f5f7fa;
    border-radius: 4px;

    .search-form {
      display: flex;
      flex-wrap: wrap;
      gap: 10px;
    }
  }

  .amount {
    font-weight: 500;
    color: #f56c6c;
  }

  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
}

// 暗色模式适配
.dark {
  .invoice-management {
    .search-section {
      background-color: #1a1a1a;
    }

    .stat-card {
      background-color: #2b2b2b;

      .stat-info {
        .stat-title {
          color: #a0a0a0;
        }

        .stat-amount {
          color: #ffffff;
        }
      }
    }
  }
}

.invoice-preview-dialog {
  :deep(.el-dialog) {
    margin: 0 !important;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    max-height: 80vh;
    display: flex;
    flex-direction: column;
  }

  :deep(.el-dialog__header) {
    margin: 0;
    padding: 20px;
    border-bottom: 1px solid #dcdfe6;
  }

  :deep(.el-dialog__body) {
    padding: 0;
    flex: 1;
    overflow: hidden;
  }

  :deep(.el-dialog__footer) {
    margin: 0;
    padding: 20px;
    border-top: 1px solid #dcdfe6;
  }

  .invoice-preview-wrapper {
    height: 100%;
    max-height: calc(80vh - 140px);
    overflow-y: auto;
    overflow-x: hidden;

    &::-webkit-scrollbar {
      width: 6px;
    }

    &::-webkit-scrollbar-thumb {
      background-color: #909399;
      border-radius: 3px;
    }

    &::-webkit-scrollbar-track {
      background-color: #f5f7fa;
    }
  }
}

.invoice-preview {
  background: #fff;
  padding: 30px;

  .invoice-header {
    text-align: center;
    margin-bottom: 30px;

    .invoice-title {
      font-size: 24px;
      font-weight: bold;
      margin-bottom: 15px;
    }

    .invoice-no,
    .invoice-date {
      font-size: 14px;
      color: #666;
      margin: 5px 0;
    }
  }

  .invoice-body {
    .buyer-info,
    .seller-info,
    .invoice-items {
      margin-bottom: 30px;

      h3 {
        font-size: 16px;
        margin-bottom: 15px;
        color: #333;
      }
    }

    .invoice-summary {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin: 20px 0;
      padding: 15px;
      background: #f8f9fa;
      border-radius: 4px;

      .amount-in-words {
        font-size: 14px;
        color: #666;
      }

      .amount-summary {
        font-size: 16px;

        .amount {
          font-weight: bold;
          color: #f56c6c;
          margin-left: 10px;
        }
      }
    }

    .invoice-footer {
      display: flex;
      justify-content: space-between;
      align-items: flex-end;
      margin-top: 30px;
      padding-top: 20px;
      border-top: 1px solid #eee;

      .stamps {
        text-align: right;

        .stamp {
          margin: 10px 0;
          font-size: 14px;
          color: #666;
        }
      }
    }
  }
}

// 暗色模式适配
:deep(.dark) {
  .el-dialog {
    background: #1a1a1a;
  }

  .el-dialog__header {
    border-bottom-color: #4c4d4f;
  }

  .el-dialog__footer {
    border-top-color: #4c4d4f;
  }

  .invoice-preview-wrapper {
    &::-webkit-scrollbar-thumb {
      background-color: #4c4d4f;
    }

    &::-webkit-scrollbar-track {
      background-color: #2b2b2b;
    }
  }

  .invoice-preview {
    background: #1a1a1a;

    .invoice-header {
      .invoice-title {
        color: #fff;
      }

      .invoice-no,
      .invoice-date {
        color: #909399;
      }
    }

    .invoice-body {
      .buyer-info,
      .seller-info,
      .invoice-items {
        h3 {
          color: #e5eaf3;
        }
      }

      :deep(.el-descriptions) {
        .el-descriptions__title {
          color: #e5eaf3;
        }

        .el-descriptions__label {
          color: #909399;
        }

        .el-descriptions__content {
          color: #e5eaf3;
        }
      }

      :deep(.el-table) {
        background-color: #1a1a1a;

        th.el-table__cell {
          background-color: #2b2b2b;
          color: #e5eaf3;
          border-bottom: 1px solid #4c4d4f;
        }

        td.el-table__cell {
          background-color: #1a1a1a;
          color: #e5eaf3;
          border-bottom: 1px solid #4c4d4f;
        }

        &::before {
          background-color: #4c4d4f;
        }
      }

      .invoice-summary {
        background: #2b2b2b;

        .amount-in-words {
          color: #909399;
        }

        .amount-summary {
          color: #e5eaf3;
        }
      }

      .invoice-footer {
        border-top-color: #4c4d4f;

        .stamps {
          .stamp {
            color: #909399;
          }
        }
      }
    }
  }
}

@media print {
  .el-dialog__header,
  .el-dialog__footer {
    display: none !important;
  }

  .invoice-preview {
    padding: 0;
  }

  .invoice-preview-wrapper {
    overflow: visible;
    height: auto;
  }
}

/* 空状态样式 */
.empty-state {
  padding: 40px 0;
  text-align: center;
}

.empty-text {
  font-size: 16px;
  color: var(--el-text-color-secondary);
  margin-top: 10px;
}

.empty-subtext {
  font-size: 14px;
  color: var(--el-text-color-placeholder);
  margin-top: 5px;
}

.mt-4 {
  margin-top: 16px;
}
</style>
